package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dao.EmployeeDao;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.web.R;
import com.itheima.reggie.entity.dto.employee.EmpAddDTO;
import com.itheima.reggie.entity.dto.employee.EmpUpdateDTO;
import com.itheima.reggie.entity.dto.LoginDTO;
import com.itheima.reggie.web.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

/**
 * 员工业务层实现类
 *
 * @Name : EmployeeServiceImpl
 * @Author : WuQiang
 * @Date : 2022-08-08 19:34
 * @Description : 员工业务层实现类
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeDao, Employee> implements EmployeeService {
    @Override
    public R login(LoginDTO dto) {
        //1、TODO 参数校验
        if (StringUtils.isBlank(dto.getUsername())) {
            throw new BusinessException("用户名不能为空");
        }
        if (StringUtils.isBlank(dto.getPassword())) {
            throw new BusinessException("密码能为空");
        }
        //2、核心业务
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, dto.getUsername());
        Employee employee = this.getOne(wrapper);
        if (employee == null) {
            //查无此人
            throw new BusinessException("当前用户不存在！");
        }
        //对用户输入的密码进行加密比对是否相等
        String password = dto.getPassword().trim();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
           throw new BusinessException("密码错误，请重试");
        }

        //查看员工状态
        if (employee.getStatus() == 0) {
            throw new BusinessException("该账号已被禁用，请联系管理员后重试");
        }

        //将敏感信息设置为空
        employee.setPassword("");
        employee.setIdNumber("");


        return R.success("登录成功", employee);
    }

    @Override
    public R getEmpByPage(Long page, Long pageSize, String name) {
        //1、参数校验
        if (ObjectUtils.isEmpty(page) || ObjectUtils.isEmpty(pageSize)) {
            throw new BusinessException("参数非法");
        }
        if (page <= 0) {
            page = 1L;
        }
        if (pageSize <= 0) {
            pageSize = 10L;
        }
        //2、具体业务
        Page<Employee> pages = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> lqw = Wrappers.lambdaQuery(Employee.class);
        lqw.like(StringUtils.isNotBlank(name), Employee::getName, name)
                .orderByDesc(Employee::getUpdateTime)
                //  投影查询
                .select(Employee::getId, Employee::getUsername, Employee::getName, Employee::getPhone, Employee::getStatus);
        this.page(pages, lqw);
        return R.success("查询成功", pages);
    }

    @Override
    public Boolean saveEmp(EmpAddDTO dto) {
        //TODO 1、参数校验
        //2、核心业务
        Employee employee = checkEmployeeWithUsername(dto);
        //设置默认属性
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(0);

        return this.save(employee);
    }

    @Override
    public Boolean updateEmpStatus(EmpUpdateDTO dto) {
        //1、参数校验
        if (ObjectUtils.isEmpty(dto.getId())) {
            throw new BusinessException("参数非法");
        }
        Integer status = dto.getStatus();
        if (ObjectUtils.isEmpty(status) || (status != 0 && status != 1)) {
            throw new BusinessException("参数非法");
        }

        //2、核心业务
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto, employee);
        return this.updateById(employee);

    }

    @Override
    public Boolean updateEmpByCondition(EmpUpdateDTO dto) {
        // TODO: 2022/8/11 参数校验

        //2、核心业务
        //2.1、通过用户名查询用户名是否存在
        Employee employee = checkEmployeeWithUsername(dto);
        return this.updateById(employee);

    }

    @Override
    public Boolean updateEmp(EmpUpdateDTO dto) {
        if (dto.getStatus() != null) {
            return this.updateEmpStatus(dto);
        }
        return this.updateEmpByCondition(dto);
    }

    /**
     * 通用方法
     * 通过用户名查询 校验用户名唯一性
     *
     * @param dto
     * @return
     */
    private Employee checkEmployeeWithUsername(EmpAddDTO dto) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto, employee);
        //2.1、先查在增
        LambdaQueryWrapper<Employee> lqw = Wrappers.lambdaQuery(Employee.class);
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee one = this.getOne(lqw);
        if (one != null) {
            //该用户已存在
            //避免查询到自己产生的bug
            if (!one.getId().equals(employee.getId())) {
                throw new BusinessException("用户名：" + employee.getUsername() + "太受欢迎了，请换个后重试.");
            }
        }
        return employee;
    }
}
